<script setup>
import NavBar from './NavBar.vue'
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getAllRoles } from '../api/role';
import { getAllQuestionnaires } from '../api/questionnaire'; // 导入获取问卷的方法

const router = useRouter();
const isHome = ref(true);
const showLoginDropdown = ref(false);
const showLoginAlert = ref(false);
// 添加选择的版本状态
const selectedVersion = ref('');
// 添加选择的角色状态
const selectedRole = ref('');
// 添加功能提示框状态
const showFeaturePrompt = ref(false);
// 当前功能名称
const currentFeature = ref('');
// 提示框位置
const promptPosition = ref({ top: 0, left: 0 });
// 存储从后端获取的角色名称列表
const availableRoles = ref([]);
// 存储从后端获取的问卷列表
const questionnaires = ref([]);

// 新增：保存选中的角色对象和问卷对象
const selectedRoleObj = ref({ id: '', roleName: '' });
const selectedQuestionnaireObj = ref({ id: '', queslistName: '' });

// 存储所有角色id和名字的映射
const roleMap = ref({});
// 存储所有问卷id和名字的映射
const questionnaireMap = ref({});

// 只保存选中的角色id和问卷id
const selectedRoleId = ref('');
const selectedQueslistId = ref('');

onMounted(async () => {
  try { 
    // 获取所有角色
    const roleResult = await getAllRoles();
    if (roleResult && roleResult.code === 0 && roleResult.data) {
      availableRoles.value = roleResult.data;
      // 构建角色id和名字的映射
      roleMap.value = {};
      roleResult.data.forEach(role => {
        roleMap.value[role.id] = role.rolename;
      });
      console.log('角色映射:', roleMap.value);
    } else {
      console.error('获取角色列表失败:', roleResult);
    }
    
    // 获取所有问卷
    const quesResult = await getAllQuestionnaires();
    if (quesResult && quesResult.code === 0 && quesResult.data) {
      questionnaires.value = quesResult.data;
      // 构建问卷id和名字的映射
      questionnaireMap.value = {};
      quesResult.data.forEach(q => {
        questionnaireMap.value[q.id] = q.queslistName;
      });
      console.log('问卷映射:', questionnaireMap.value);
    } else {
      console.error('获取问卷列表失败:', quesResult);
    }
  } catch (error) {
    console.error('获取数据出错:', error);
  }
});

// 修改角色选择逻辑
const selectRole = (roleName) => {
  const roleObj = availableRoles.value.find(role => role.rolename === roleName);
  if (!roleObj) {
    ElMessage({
      message: `暂时还未开放对${roleName}的体质辨识测试`,
      type: 'warning',
      duration: 2000
    });
    return;
  }
  selectedRole.value = roleName;
  selectedRoleId.value = roleObj.id;
  // 新增：保存到localStorage
  localStorage.setItem('selectedRoleId', roleObj.id);
  isHome.value = false;
  selectedVersion.value = '';
};

// 修改版本选择逻辑
const selectVersion = (versionName) => {
  const questionnaireObj = questionnaires.value.find(q => q.queslistName === versionName);
  if (questionnaireObj) {
    selectedQueslistId.value = questionnaireObj.id;
    // 新增：保存到localStorage
    localStorage.setItem('selectedQueslistId', questionnaireObj.id);
  } else {
    selectedQueslistId.value = '';
    localStorage.removeItem('selectedQueslistId');
  }
  selectedVersion.value = versionName;
  router.push({
    path: '/test',
    query: {
      role: selectedRole.value,
      version: versionName
    }
  });
};

// 关闭功能提示框
const closeFeaturePrompt = () => {
  showFeaturePrompt.value = false;
};

// 从提示框跳转到登录页面
const goToLoginFromPrompt = () => {
  showFeaturePrompt.value = false;
  router.push('/login');
};
</script>

<template>
  <div class="main-container">
    <NavBar />
    <div class="content">
      <h1 class="title">中医体质辨识系统</h1>
      
      <!-- 角色选择部分，根据isHome状态显示或隐藏 -->
      <div class="role-section" v-if="isHome">
        <h2 class="role-title">请选择您的角色</h2>
        <div class="role-icons">
          <div class="role-item" @click="selectRole('儿童')">
            <div class="role-icon">
              <img src="../img/child.jpg" alt="儿童">
            </div>
            <div class="role-name">儿童</div>
          </div>
          
          <div class="role-item" @click="selectRole('成人')">
            <div class="role-icon">
              <img src="../img/adult.jpg" alt="成人">
            </div>
            <div class="role-name">成人</div>
          </div>
          
          <div class="role-item" @click="selectRole('老年')">
            <div class="role-icon">
              <img src="../img/elderly.jpg" alt="老年">
            </div>
            <div class="role-name">老年</div>
          </div>
          
          <div class="role-item" @click="selectRole('孕妇')">
            <div class="role-icon">
              <img src="../img/pregnant.jpg" alt="孕妇">
            </div>
            <div class="role-name">孕妇</div>
          </div>
          
          <div class="role-item" @click="selectRole('备孕')">
            <div class="role-icon">
              <img src="../img/planning.jpg" alt="备孕">
            </div>
            <div class="role-name">备孕</div>
          </div>
        </div>
      </div>
      
      <!-- 非首页状态的内容 -->
      <div v-if="!isHome" class="non-home-content">
        <p>您已选择角色：<span class="selected-role">{{ selectedRole }}</span>，请选择问卷版本</p>
        
        <!-- 版本选择按钮 -->
        <div class="version-buttons">
          <!-- 使用从后端获取的问卷名称替换固定的版本名称 -->
          <button 
            v-for="questionnaire in questionnaires" 
            :key="questionnaire.id"
            class="version-btn" 
            :class="{ active: selectedVersion === questionnaire.queslistName }"
            @click="selectVersion(questionnaire.queslistName)">
            {{ questionnaire.queslistName }}
          </button>
          
          <!-- 如果没有获取到问卷，显示默认的三个版本 -->
          <template v-if="questionnaires.length === 0">
            <button 
              class="version-btn" 
              :class="{ active: selectedVersion === '简洁版' }"
              @click="selectVersion('简洁版')">
              简洁版
            </button>
            <button 
              class="version-btn" 
              :class="{ active: selectedVersion === '普通版' }"
              @click="selectVersion('普通版')">
              普通版
            </button>
            <button 
              class="version-btn" 
              :class="{ active: selectedVersion === '详细版' }"
              @click="selectVersion('详细版')">
              详细版
            </button>
          </template>
        </div>
      </div>
      
      <!-- 移除"前往测试页面"按钮 -->
    </div>

    <!-- 登录提示弹窗 -->
    <div class="login-alert" v-if="showLoginAlert">
      <div class="alert-content">
        <p>该功能需要登录后解锁</p>
      </div>
    </div>

    <!-- 功能提示小弹窗 -->
    <div class="feature-prompt-mini" v-if="showFeaturePrompt" 
         :style="{ top: promptPosition.top + 'px', left: promptPosition.left + 'px' }">
      <div class="prompt-arrow"></div>
      <div class="prompt-content">
        <p>{{ currentFeature === 'personal' ? '个人中心' : '数据分析' }}需要登录</p>
        <div class="prompt-buttons">
          <button class="cancel-btn" @click="closeFeaturePrompt">取消</button>
          <button class="login-btn" @click="goToLoginFromPrompt">去登录</button>
        </div>
      </div>
    </div>
  </div>
</template>



<style scoped src="../css/main.css"></style>